var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
const SALT_WORK_FACTOR = 10;

var UserSchema = new mongoose.Schema(
	{
		username: {
			type: String,
			maxlength: 18
		},
		password: String,
		role: {
			type: Number,
			default: 0
		}
	}, 
	{
		timestamps: true
	}
);

UserSchema.pre('save', function(next) {
	var user = this;
	console.log('in userSchema pre: ', this);
	bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
		if (err) {
			return next(err);
		}
		bcrypt.hash(user.password, salt, function(err, hash) {
			if (err) {
				return next(err);
			}
			user.password = hash;
			console.log(user);
			next();
		})
	})
})

UserSchema.methods = {
	comparePassword: function (_password, cb) {
		console.log(this.password);
		bcrypt.compare(_password, this.password, function (err, isMatch) {
			if (err) {
				return cb(err);
			}
			cb(null, isMatch);
		});
	}
}

module.exports = mongoose.model('User', UserSchema);
